package dj.service.impl;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import dj.Constant;
import dj.dao.BaseDao;
import dj.dwr.MessagePush;
import dj.model.Friend;
import dj.model.FriendExtend;
import dj.model.FriendGroup;
import dj.model.TalkContext;
import dj.model.Tuser;
import dj.pageModel.PtalkContext;
import dj.service.FriendService;
import dj.service.TalkContextService;
import dj.service.UserService;

@Service("talkContextService")
public class TalkContextServiceImpl implements TalkContextService {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(TalkContextServiceImpl.class);

	private BaseDao<TalkContext> talkContextDao;

	private UserService userService;

	private FriendService friendService;

	public BaseDao<TalkContext> getTalkContextDao() {
		return talkContextDao;
	}

	@Autowired
	public void setTalkContextDao(BaseDao<TalkContext> talkContextDao) {
		this.talkContextDao = talkContextDao;
	}

	public UserService getUserService() {
		return userService;
	}

	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public FriendService getFriendService() {
		return friendService;
	}

	@Autowired
	public void setFriendService(FriendService friendService) {
		this.friendService = friendService;
	}

	public void editReadState(String userid, String messageid) {
		Map<String, Map<String, PtalkContext>> userMessage = MessagePush.getUserMessage();
		PtalkContext pc = userMessage.get(userid).get(messageid);
		if (null != pc) {
			pc.setRead(true);
		}
	}

	public void updateContextIsread() {
		Map<String, Map<String, PtalkContext>> userMessage = MessagePush.getUserMessage();
		for (Map<String, PtalkContext> pcs : userMessage.values()) {
			//new一个map 用于循环，否则更改原map循环会出现问题
			Map<String, PtalkContext> npcs = new LinkedHashMap<String, PtalkContext>(pcs);
			// 循环用户消息，更新数据库
			for (PtalkContext pc : npcs.values()) {
				// 如果用户已读消息，则更新数据库
				if (pc.isRead()) {
					TalkContext tc = new TalkContext();
					BeanUtils.copyProperties(pc, tc);
					tc.setIsRead(Constant.STATE_READ);
					// 更新数据库
					talkContextDao.update(tc);
					// 释放掉内存
					pcs.remove(pc.getId());
				}
			}
		}
	}

	public void saveContextToDb(PtalkContext pc) {
		TalkContext tc = new TalkContext();
		BeanUtils.copyProperties(pc, tc);
		if (pc.isRead()) {
			tc.setIsRead(Constant.STATE_READ);
		} else {
			tc.setIsRead(Constant.STATE_UNREAD);
		}
		// 更新数据库
		talkContextDao.save(tc);
	}

	public void initUnreadContext() {
		logger.info("加载未读消息...");
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("isRead", Constant.STATE_UNREAD);
		List<TalkContext> tcls = talkContextDao.find("from TalkContext where isRead=:isRead", params);

		for (TalkContext tc : tcls) {
			PtalkContext pc = new PtalkContext();
			BeanUtils.copyProperties(tc, pc);
			pc.setRead(false);
			// 接收人
			Tuser friend = userService.getUserById(tc.getReceiveUserid());
			//接收人的所有好友组，用于闪烁消息用
			List<FriendGroup> fgls = friendService.getFriendGroup(tc.getReceiveUserid());
			//获取好友信息
			Friend f = friendService.getFriend(tc.getReceiveUserid(), tc.getSendUserid());
			pc.setReceiveUsername(friend.getName());
			pc.setFgls(fgls);
			//备注名称
			String remarkName = "";
			if (null != f && null != f.getFriendExtends() && f.getFriendExtends().size() > 0) {
				FriendExtend fe = f.getFriendExtends().iterator().next();
				remarkName = fe.getRemarkName();
			}
			String friendName = "";
			if("".equals(remarkName)) {
				if(null != f.getTuser().getDisplayName() && !"".equals(f.getTuser().getDisplayName().trim())) {
					friendName = f.getTuser().getDisplayName() + "(" + f.getTuser().getName() + ")";
				} else {
					friendName = f.getTuser().getName();
				}
			} else {
				friendName = remarkName + "(" + f.getTuser().getName() + ")";
			}
			pc.setSendUsername(friendName);
			//把消息放到内存中
			if (null != MessagePush.getUserMessage().get(tc.getReceiveUserid())) {
				MessagePush.getUserMessage().get(tc.getReceiveUserid()).put(tc.getId(), pc);
			} else {
				Map<String, PtalkContext> pcm = new LinkedHashMap<String, PtalkContext>();
				pcm.put(tc.getId(), pc);
				MessagePush.getUserMessage().put(tc.getReceiveUserid(), pcm);
			}
		}

	}

}
